/**
 * 创建节点模板 暂时未使用
 * @param panel
 * @param graph
 * @param name
 * @param icon
 * @param style
 * @param width
 * @param height
 * @param value
 * @param parentNode
 */
function insertEdgeTemplate(panel, graph, name, icon, style, width, height, value, parentNode){
		var cells = [new mxCell((value != null) ? value : '', new mxGeometry(0, 0, width, height), style)];
		cells[0].geometry.setTerminalPoint(new mxPoint(0, height), true);
		cells[0].geometry.setTerminalPoint(new mxPoint(width, 0), false);
		cells[0].edge = true;
		var funct = function(graph, evt, target){
			cells = graph.getImportableCells(cells);
			if(cells.length > 0){
				var validDropTarget = (target != null) ? graph.isValidDropTarget(target, cells, evt) : false;
				var select = null;
				if(target != null && !validDropTarget){
					target = null;
				}
				var pt = graph.getPointForEvent(evt);
				var scale = graph.view.scale;
				pt.x -= graph.snap(width / 2);
				pt.y -= graph.snap(height / 2);
				select = graph.importCells(cells, pt.x, pt.y, target);
				GraphEditor.edgeTemplate = select[0];
				graph.scrollCellToVisible(select[0]);
				graph.setSelectionCells(select);
			}
		};
		var node = panel.addTemplate(name, icon, parentNode, cells);
		var installDrag = function(expandedNode){
			if (node.ui.elNode != null){
				var dragPreview = document.createElement('div');
				dragPreview.style.border = 'dashed black 1px';
				dragPreview.style.width = width+'px';
				dragPreview.style.height = height+'px';
				mxUtils.makeDraggable(node.ui.elNode, graph, funct, dragPreview, -width / 2, -height / 2,graph.autoscroll, true);
			}
		};
		if(!node.parentNode.isExpanded()){
			panel.on('expandnode', installDrag);
		}else{
			installDrag(node.parentNode);
		}
		return node;
};

/**
 * 添加元素右上角的删除图标
  * @param graph
 * @param cell
 * @param addDeleteIcon
 */
function addOverlays(graph, cell, addDeleteIcon){  
    var overlay = new mxCellOverlay(new mxImage('images/add.png', 24, 24), 'Add child');  
    overlay.cursor = 'hand';  
    overlay.align = mxConstants.ALIGN_CENTER;  
    overlay.addListener(mxEvent.CLICK, mxUtils.bind(this, function(sender, evt){  
        addChild(graph, cell);  
    }));  
    graph.addCellOverlay(cell, overlay);  
    if (addDeleteIcon){  
        overlay = new mxCellOverlay(new mxImage('images/close.png', 30, 30), 'Delete');  
        overlay.cursor = 'hand';  
        overlay.offset = new mxPoint(-4, 8);  
        overlay.align = mxConstants.ALIGN_RIGHT;  
        overlay.verticalAlign = mxConstants.ALIGN_TOP;  
        overlay.addListener(mxEvent.CLICK, mxUtils.bind(this, function(sender, evt){  
            deleteSubtree(graph, cell);  
        }));  
        graph.addCellOverlay(cell, overlay);  
    }  
};

/**
 * 添加子元素
  * @param graph
 * @param cell
 * @returns {*}
 */
function addChild(graph, cell){  
    var model = graph.getModel();  
    var parent = graph.getDefaultParent();  
    var vertex;  
    model.beginUpdate();  
    try {  
        vertex = graph.insertVertex(parent, null, 'Double click to set name');  
        var geometry = model.getGeometry(vertex);  
        var size = graph.getPreferredSizeForCell(vertex);  
        geometry.width = size.width;  
        geometry.height = size.height;  
        var edge = graph.insertEdge(parent, null, '', cell, vertex);  
        edge.geometry.x = 1;  
        edge.geometry.y = 0;  
        edge.geometry.offset = new mxPoint(0, -20);  
    }finally{  
        model.endUpdate();  
    }  
    return vertex;  
};

/**
 * 导入拓扑图
 * @param graph
 * @param history
 */
function imp(graph,history){

}

/**
 *
 * @param id
 */
function doImpl(id){
    msgTishCallFnBoot("确定导入该拓扑图？",function(){

    })
}

/**
 * 连线样式设置虚线
 * @param editor
 */
function connectEdge(editor){
	if (editor.defaultEdge != null){
		editor.defaultEdge.style = 'straightEdge';
	}
}

/**
 *
 * @param graph
 * @param history
 */
function importP(graph,history){
    //initScroll()
	console.log("importP---");
    imp(graph,history)
}


/**
 * 导出文件
 */
function exportP(graph){
    //获取mxgraph拓扑图数据
    //var enc = new mxCodec(mxUtils.createXmlDocument());
    //var node1 = enc.encode(graph.getModel());
    //var mxgraphxml = mxUtils.getXml(node1);
    var enc = new mxCodec(mxUtils.createXmlDocument());
    var node = enc.encode(graph.getModel());
    var mxgraphxml = mxUtils.getPrettyXml(node);
    mxgraphxml = mxgraphxml.replace(/\"/g,"'");
    //mxgraphxml = encodeURIComponent(mxgraphxml);

    var xmlDoc = mxUtils.createXmlDocument();
    var root = xmlDoc.createElement('output');
    xmlDoc.appendChild(root);
    var xmlCanvas = new mxXmlCanvas2D(root);
    var imgExport = new mxImageExport();
    imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
    var bounds = graph.getGraphBounds();
    var w = Math.round(bounds.x + bounds.width + 4);
    var h = Math.round(bounds.y + bounds.height + 4);
    var imgxml = mxUtils.getXml(root);
    //imgxml = "<output>"+imgxml+"</output>";
    //imgxml = encodeURIComponent(imgxml);

    doExportP(mxgraphxml,w,h,imgxml);
}

/**
 *
 * @param mxgraphxml
 * @param w
 * @param h
 * @param imgxml
 */
function doExportP(mxgraphxml,w,h,imgxml){
    msgTishCallFnBoot("确定导出？",function(){
        $('#mxgraphxml').val(mxgraphxml);
        $('#imgxml').val(imgxml);
        $('#w').val(w);
        $('#h').val(h);
        submitBFormCallFn('BaseForm',baseUrl+'create',function(result){
            try {
                console.log(result);
                downOrExportB(baseUrl+'export?name='+result);
            } catch (e) {

            }
        });
    })
}

/**
 *
 * @param graph
 */
function saveP(graph){
    //获取mxgraph拓扑图数据
    //var enc = new mxCodec(mxUtils.createXmlDocument());
    //var node1 = enc.encode(graph.getModel());
    //var mxgraphxml = mxUtils.getXml(node1);
    var enc = new mxCodec(mxUtils.createXmlDocument());
    var node = enc.encode(graph.getModel());
    var mxgraphxml = mxUtils.getPrettyXml(node);
    mxgraphxml = mxgraphxml.replace(/\"/g,"'");
    //mxgraphxml = encodeURIComponent(mxgraphxml);

    var xmlDoc = mxUtils.createXmlDocument();
    var root = xmlDoc.createElement('output');
    xmlDoc.appendChild(root);
    var xmlCanvas = new mxXmlCanvas2D(root);
    var imgExport = new mxImageExport();
    imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
    var bounds = graph.getGraphBounds();
    var w = Math.round(bounds.x + bounds.width + 4);
    var h = Math.round(bounds.y + bounds.height + 4);
    var imgxml = mxUtils.getXml(root);
    //imgxml = "<output>"+imgxml+"</output>";
    //imgxml = encodeURIComponent(imgxml);
    saveDesign(mxgraphxml,w,h,imgxml);

    // //initScroll()
    // //获取mxgraph拓扑图数据
    // //var enc = new mxCodec(mxUtils.createXmlDocument());
    // //var node1 = enc.encode(graph.getModel());
    // //var mxgraphxml = mxUtils.getXml(node1);
    // var enc = new mxCodec(mxUtils.createXmlDocument());
    // var node = enc.encode(graph.getModel());
    // var mxgraphxml = mxUtils.getPrettyXml(node);
    // mxgraphxml = mxgraphxml.replace(/\"/g,"'");
    // //mxgraphxml = encodeURIComponent(mxgraphxml);
    // try{
    //     var xmlDoc = mxUtils.createXmlDocument();
    //     var root = xmlDoc.createElement('output');
    //     xmlDoc.appendChild(root);
    //     var xmlCanvas = new mxXmlCanvas2D(root);
    //     var imgExport = new mxImageExport();
    //     imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
    //     var bounds = graph.getGraphBounds();
    //     var w = Math.round(bounds.x + bounds.width + 4);
    //     var h = Math.round(bounds.y + bounds.height + 4);
    //     var imgxml = mxUtils.getXml(root);
    //     //imgxml = "<output>"+imgxml+"</output>";
    //     //imgxml = encodeURIComponent(imgxml);
    //
    //     saveDesign(mxgraphxml,w,h,imgxml);
    // }catch (e){
    //
    // }

}

/**
 *
 */
function closeJehcLcWin(){
    $('#jehcLcModal').modal('hide');
}

/**
 *
 */
function initScroll(){
    // $("#sidebarContainer").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#diagramContainer").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false}); // First scrollable DIV
}

/**
 *
 */
function nodeScroll(){
    // $("#mportletId").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#mportletId1").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#TabCol").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
}


/**
 *
 * @param flag
 * @param graph
 */
function linetostyle(flag,graph){
    // var line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/default-style.xml';
    // if(flag == 0){
    //     //如果为1直线
    //     line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/default-style.xml';
    // }else if(flag == 1){
    //     //如果为1曲线
    //     line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/bight-style.xml';
    // }
    // var history = new mxUndoManager();
    // //载入默认样式
    // var node = mxUtils.load(line_style).getDocumentElement();
    // var dec = new mxCodec(node.ownerDocument);
    // dec.decode(node, graph.getStylesheet());
    // var edgeStyle = graph.getStylesheet().getDefaultEdgeStyle();
    // //edgeStyle[mxConstants.STYLE_EDGE] = mxEdgeStyle.TopToBottom;
    // edgeStyle['gradientColor'] = '#c0c0c0';
    // edgeStyle['strokeColor'] = '#c0c0c0'; //更改连线默认样式此处为颜色
    // edgeStyle['dashed'] = '1'; //虚线
    // edgeStyle['strokeWidth'] = 0.1;
    // edgeStyle['fontSize'] = '8';
    // edgeStyle['fontColor'] = '#000';
    // edgeStyle['arrowWidth'] = 0.1;
    // graph.alternateEdgeStyle = 'elbow=vertical';
    // graph.refresh();
    // Ext.getCmp('lc_process_mxgraph_style').setValue(flag);
}

/**
 * 载入XML流程图
 * @param graph
 * @param xml
 */
function loadXml(graph,xml){
    graph.getModel().beginUpdate();
    try{
        if(xml != null && xml.length > 0){
            var doc = mxUtils.parseXml(xml);
            var dec = new mxCodec(doc);
            dec.decode(doc.documentElement, graph.getModel());
        }
    }finally{
        graph.getModel().endUpdate();
        graph.refresh();
    }
    setTimeout(function(){
        resetZxLine(graph);
    },100);
}

/**
 *
 */
$(document).ready(function() {
    $('#BaseForm').bootstrapValidator({
        message: '此值不是有效的'
    });
});

/**
 * 保存
 * @param mxgraphxml
 * @param w
 * @param h
 * @param imgxml
 */
function saveDesign(mxgraphxml,w,h,imgxml){
    msgTishCallFnBoot("确定保存？",function(){
        $('#graph_site_mxgraph').val(mxgraphxml);
        $('#imgxml').val(imgxml);
        $('#w').val(w);
        $('#h').val(h);
        $('#gridColor').val(ThizViewPort.editorUi.editor.graph.view.gridColor);
        var gridBackGround = ThizViewPort.editorUi.editor.graph.background;
        if(undefined === gridBackGround || gridBackGround == null || gridBackGround == ""){
            gridBackGround = "#fff";
        }
        $('#gridBackGround').val(gridBackGround);
        $("#stationId").val("1");
        submitBFormCallFn('BaseForm',monitorModules+'/graphDesign/saveGraphSite',function(result){
            try {
                if(typeof(result.success) != "undefined"){
                    if(result.success){
                        window.parent.toastrBoot(3,result.message);
                        $("#graph_site_id").val(result.data);
                    }else{
                        window.parent.toastrBoot(4,result.message);
                    }
                }
            } catch (e) {

            }
        });
    })
}


/**
 * 将字符串转换XML
 * @param xmlobj
 * @returns {*}
 */
function printString(xmlobj){
    var xmlDom;
    //IE
    if(document.all){
        xmlDom=new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(xmlobj);
    }
    //非IE
    else {
        xmlDom = new DOMParser().parseFromString(xmlobj, "text/xml");
    }
    return xmlDom;
}


/**
 *
 * @param graph
 */
function resetZxLine(graph){
    var allLines =graph.getModel().cells;
    for(var i in allLines){
        var cell = allLines[i];
        if(cell.nodeType == "zxLine"){
            // Adds animation to edge shape and makes "pipe" visible
            graph.getModel().beginUpdate();
            try{
                var state = graph.view.getState(cell);
                if(null != state){
                    state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
                    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
                    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
                    state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
                }
            }finally{
                // Updates the display
                graph.getModel().endUpdate();
            }
        }
    }
}

/**
 *
 * @param graph
 * @param parent
 * @param x
 * @param y
 */
function aminLine(graph,parent,x,y){
    var vertexStyle = 'shape=cylinder;strokeWidth=2;fillColor=#ffffff;strokeColor=black;' +
        'gradientColor=#a0a0a0;fontColor=black;fontStyle=1;spacingTop=14;';
    graph.getModel().beginUpdate();
    try{
        var v1 = graph.insertVertex(parent, null, 'Pump', x, y, 48, 48,vertexStyle);
        var v2 = graph.insertVertex(parent, null, 'Tank', x+160, y, 48, 48,vertexStyle);
        var edge = graph.insertEdge(parent, null, '', v1, v2,'strokeWidth=3;endArrow=block;endSize=2;endFill=1;strokeColor=black;rounded=1;');
        edge.geometry.points = [new mxPoint(x, y)];
        graph.orderCells(true, [edge]);
    }finally{
        // Updates the display
        graph.getModel().endUpdate();
    }

    // Adds animation to edge shape and makes "pipe" visible
    var state = graph.view.getState(edge);
    // state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
    state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
    graph.getModel().beginUpdate();
    try {
        graph.removeCells([v1], false);
        graph.removeCells([v2], false);
    }finally{
        // Updates the display
        graph.getModel().endUpdate();
    }
}

/**
 *
 * @param graph
 * @param edge
 */
function addAnimationEdge(graph,edge){
    // Adds animation to edge shape and makes "pipe" visible
    graph.getModel().beginUpdate();
    try{
        var state = graph.view.getState(edge);
        state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
        state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
        state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
        state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
    }finally{
        // Updates the display
        graph.getModel().endUpdate();
    }
}

/**
 *
 * @param cell
 * @param graph
 */
function clearCELLText(cell,graph){
    if(null == cell || undefined === cell){
        return;
    }
    //如果节点是连线 开关，点，改变填充颜色
    if(cell.nodeType == 'onoffclose2' ||
        cell.nodeType == 'onoffopen2' ||
        cell.nodeType == 'onOffClose' ||
        cell.nodeType == 'onOffOpen' ||
        cell.nodeType == "point"){
        setTimeout(function(){
            graph.getModel().beginUpdate();
            try{
                // graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, cell.fills, [cell]);
                cell.value="";//清空节点值
            } finally {
                graph.getModel().endUpdate();
            }
        },"500");
        return;
    }
    setTimeout(function(){
        graph.getModel().beginUpdate();
        try{
            if(cell.nodeType == "Text"){
                cell.value="文本";
                return;
            }else{
                cell.value="";//清空节点值
            }
        } finally {
            graph.getModel().endUpdate();
        }
    },"500");
}

/**
 *
 * @param cell
 * @param graph
 */
function svgToBase64(cell,graph){
    if(null == cell || undefined === cell){
        return;
    }
    //如果节点是连线 开关，点，改变填充颜色
    if(cell.nodeType == 'onoffclose2' ||
        cell.nodeType == 'onoffopen2' ||
        cell.nodeType == 'onOffClose' ||
        cell.nodeType == 'onOffOpen' ||
        cell.nodeType == "point"){
        setTimeout(function(){
            graph.getModel().beginUpdate();
            try{
                graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, cell.fills, [cell]);
                cell.value="";//清空节点值
            } finally {
                graph.getModel().endUpdate();
            }
        },"500");
        return;
    }
    // console.log("geometry",cell.geometry);
    // console.log("height",cell.geometry.height);
    // console.log("width",cell.geometry.width);

    // var oldImgHref = MXSOURCESPATH+"/"+cell.image;
    // var oldImg = document.createElement('img');
    // oldImg.src = oldImgHref;
    // oldImg.onload=function(){

        try {
            var svgs = cell.svgs;
            var svgtemplate = document.getElementById("svgtemplate");
            if(svgs == null || undefined === svgs){
                return;
            }
            $("#svgtemplatePath").attr("d",svgs);

            var fills = cell.fills;//填充
            if('' != fills && fills != null && undefined !== fills){
                $("#svgtemplatePath").attr("fill",fills);
            }else{
                $("#svgtemplatePath").attr("fill","#fff");
            }

            var svgHeight = cell.svgHeight;
            if('' != svgHeight && svgHeight != null && undefined !== svgHeight) {
                $("#svgtemplate").attr("height", svgHeight);
            }else{
                $("#svgtemplate").attr("height", 120);
            }

            var svgWidth = cell.svgWidth;
            if('' != svgWidth && svgWidth != null && undefined !== svgWidth) {
                $("#svgtemplate").attr("width", svgWidth);
            }else{
                $("#svgtemplate").attr("width", 120);
            }

            var stockFill = cell.stockFill;//线条颜色
            if('' != stockFill && stockFill != null && undefined !== stockFill){
                $("#svgtemplatePath").attr("stroke",stockFill);
            }else{
                $("#svgtemplatePath").attr("stroke","#fff");
            }

            var svgCon = svgtemplate.outerHTML;
            //svg转base64;
            var svgBase64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgCon)));
            var image = new Image(); //创建一个Image对象，实现图片的预下载
            image.src = svgBase64;
            var height = cell.svgHeight;
            var width = cell.svgWidth;
            image.onload =function(){
                image.width = width;
                image.height = height;
                var canvas = document.createElement('canvas');
                // var canvasWidth = width;
                // var canvasHeight = height;
                canvas.width = width;
                canvas.height = height;
                var context = canvas.getContext('2d');
                // context.scale(cWidth/2,cHeight/2);
                // var scale =1;
                // if(height > width){
                //     scale = width / height;
                //     context.drawImage(image, (canvasWidth - canvasHeight * scale) / 2, 0, canvasHeight * scale, canvasHeight);
                // }else if (width > height) {
                //     scale = height / width
                //     context.drawImage(image, 0, (canvasHeight - canvasWidth * scale) / 2, canvasWidth, canvasWidth * scale);
                // }else {
                //     context.drawImage(image, 0, 0,canvasWidth,canvasHeight);
                // }
                context.drawImage(image, 0, 0,cell.svgWidth,cell.svgHeight);
                graph.getModel().beginUpdate();
                try{
                    //svg转png的base64编码;
                    var imgDataUri = canvas.toDataURL("image/png");
                    // imgDataUri = ""
                    // console.log("----------------",imgDataUri);
                    graph.setCellStyles(mxConstants.STYLE_IMAGE, imgDataUri.replace(';',''), [cell]);//方法一 设置图片 注意需要替换';'号
                    if(cell.nodeType != "Text"){
                        cell.value="";//清空节点值
                    }

                    //方法二也可以
                    //onOffClose[mxConstants.STYLE_IMAGE] =imgDataUri;
                    //graph.getStylesheet().putCellStyle('onOffClose_image4gray', onOffClose);

                } finally {
                    graph.getModel().endUpdate();
                }
            }
        }catch (e){
            console.log("e",e);
        }

    // }
}

/**
 * 更改线条颜色
 * @param cell
 * @param graph
 * @constructor
 */
function ChStockFill(cell,graph) {
    if (null == cell || undefined === cell) {
        return;
    }
    //如果节点是连线 开关，点，改变填充颜色
    if (cell.nodeType == 'onoffclose2' ||
        cell.nodeType == 'onoffopen2' ||
        cell.nodeType == 'onOffClose' ||
        cell.nodeType == 'onOffOpen' ||
        cell.nodeType == "point") {
        setTimeout(function () {
            graph.getModel().beginUpdate();
            try {
                graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, cell.fills, [cell]);
                cell.value = "";//清空节点值
            } finally {
                graph.getModel().endUpdate();
            }
        }, "500");
        return;
    }

    try {
        var stockFill = cell.stockFill;//线条颜色
        graph.getModel().beginUpdate();
        try{
            graph.setCellStyles("stockFill", stockFill, [cell]);
            if(cell.nodeType != "Text"){
                cell.value="";//清空节点值
            }
        } finally {
            graph.getModel().endUpdate();
        }
    }catch (e){
        console.log("e",e);
    }
}

//填充颜色
function ChFills(cell,graph){
    if (null == cell || undefined === cell) {
        return;
    }
    //如果节点是连线 开关，点，改变填充颜色
    if (cell.nodeType == 'onoffclose2' ||
        cell.nodeType == 'onoffopen2' ||
        cell.nodeType == 'onOffClose' ||
        cell.nodeType == 'onOffOpen' ||
        cell.nodeType == "point") {
        setTimeout(function () {
            graph.getModel().beginUpdate();
            try {
                graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, cell.fills, [cell]);
                cell.value = "";//清空节点值
            } finally {
                graph.getModel().endUpdate();
            }
        }, "500");
        return;
    }
    try {
        var fills = cell.fills;//填充
        graph.getModel().beginUpdate();
        try{
            graph.setCellStyles("fills", fills, [cell]);
            if(cell.nodeType != "Text"){
                cell.value="";//清空节点值
            }
        } finally {
            graph.getModel().endUpdate();
        }
    }catch (e){
        console.log("e",e);
    }
}


// function chCellColor(cell,graph){
//     if(null == cell || undefined === cell){
//         return;
//     }
//     //如果节点是连线 开关，点，改变填充颜色
//     if(cell.nodeType == 'onoffclose2' ||
//         cell.nodeType == 'onoffopen2' ||
//         cell.nodeType == 'onOffClose' ||
//         cell.nodeType == 'onOffOpen' ||
//         cell.nodeType == "point"){
//         setTimeout(function(){
//             graph.getModel().beginUpdate();
//             try{
//                 graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, cell.fills, [cell]);
//                 cell.value="";//清空节点值
//             } finally {
//                 graph.getModel().endUpdate();
//             }
//         },"500");
//         return;
//     }
//
//
//     var svgPath;
//     var stockFill = cell.stockFill;//线条颜色
//     var fills = cell.fills;//填充
//     var width = 32;
//     var height =32;
//     if(undefined != cell.svg && null != cell.svg){
//         svgPath = cell.svg;
//         // width = cell.width;
//         // height = cell.height;
//     }
//     console.log("svgPath",svgPath);
//     var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
//     svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
//     svg.setAttribute('xml:space', 'preserve')
//     svg.setAttribute('width', width)
//     svg.setAttribute('height', height)
//     svg.setAttribute('version', '1.1')
//
//     svg.setAttribute('viewBox', '0 0 '+width+' '+height)
//     svg.setAttribute('preserveAspectRatio', 'none')
//     // svg.setAttribute('style', 'shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd')
//     svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink')
//
//     var g = document.createElementNS("http://www.w3.org/2000/svg", "g")
//     g.setAttribute('id', 'G_x0020_1')
//     var metadata = document.createElementNS("http://www.w3.org/2000/svg", "metadata")
//     metadata.setAttribute('id', 'CorelCorpID_0Corel-Layer')
//     var cong = document.createElementNS("http://www.w3.org/2000/svg", "g")
//     cong.setAttribute('id', '_1828549179696')
//
//     // var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect")
//     // rect.setAttribute('class', 'fil0 str0')
//     // rect.setAttribute('x', '17')
//     // rect.setAttribute('y', '17')
//     // rect.setAttribute('width', '32')
//     // rect.setAttribute('height', '32')
//     var path = document.createElementNS("http://www.w3.org/2000/svg", "path")
//     // path.setAttribute('class', 'fil1')
//     if(null != svgPath){
//         path.setAttribute('d', svgPath)
//         path.setAttribute('stroke', stockFill)
//         path.setAttribute('fill', fills)
//     }
//
//
//     // var defs = document.createElementNS("http://www.w3.org/2000/svg", "defs")
//     // var style = document.createElementNS("http://www.w3.org/2000/svg", "style")
//     // style.setAttribute('type', 'text/css')
//     // style.innerHTML =
//     //     ".str0 {" +
//     //     "stroke: #fff; stroke-width:3;}" +
//     //     ".fil0 {fill:none }" +
//     //     ".fil1 {" +
//     //     "fill: #FF0000;}"
//     g.appendChild(metadata)
//     g.appendChild(cong)
//     // cong.appendChild(rect)
//     cong.appendChild(path)
//     // defs.appendChild(style)
//     // svg.appendChild(defs)
//     svg.appendChild(g)
//
//     try {
//         graph.getModel().beginUpdate();
//         try{
//             // var CELLStyle = new Object();
//             // CELLStyle[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_IMAGE;
//             // CELLStyle[mxConstants.STYLE_FONTSIZE] = '8';
//             // CELLStyle[mxConstants.STYLE_FONTCOLOR] = '#000';
//             // CELLStyle[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
//             // CELLStyle[mxConstants.STYLE_IMAGE] = MXSOURCESPATH+'/images/power/point.png';
//             // graph.getStylesheet().putCellStyle('CELLStyle', CELLStyle);
//             // graph.getStylesheet().putCellStyle('CELLStyle', CELLStyle);
//             graph.setCellStyles("stockFill", stockFill, [cell]);//方法一 设置图片 注意需要替换';'号
//             // graph.setCellStyles(mxConstants.STYLE_IMAGE, "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svg)))), [cell]);//方法一 设置图片 注意需要替换';'号
//             if(cell.nodeType != "Text"){
//                 cell.value="";//清空节点值
//             }
//         } finally {
//             graph.getModel().endUpdate();
//         }
//     }catch (e){
//         console.log("e",e);
//     }
// }

/**
 *
 */
function imgBase64(){}

/**
 *
 * @param cell
 * @param graph
 */
function initSidebarSvg(cell,graph){
    svgToBase64(cell,graph);
}

//
// function svgToBase64(graph,onOffClose){
//     var svgtemplate = document.querySelector(".svgtemplate");
//     var svgCon = svgtemplate.outerHTML;
//
//     //svg转base64;
//     var svgBase64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgCon)));
//
//     var image = document.createElement('img');
//     image.style.position = 'absolute';
//     image.style.marginLeft = '25px';
//     image.style.marginTop = '25px';
//     image.setAttribute('width', 50);
//     image.setAttribute('height',50);
//     image.src = svgBase64;
//     image.onload=function(){
//         //svg转png的base64编码;
//         var imgDataUri = image2Base64(image);
//         onOffClose[mxConstants.STYLE_IMAGE] = imgDataUri;
//         console.log("imgDataUri",imgDataUri);
//         graph.getStylesheet().putCellStyle('onOffClose_image4gray', onOffClose);
//     }
// }

/**
 *
 * @param img
 * @returns {string}
 */
function image2Base64(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}




/**
 * method:上传操作
 * fieldid:附件编号
 * picid:附件上传后回显图片对象编号
 * validateparameter:校验非法参数组装字符串
 * validateSize:校验大小
 * xt_path_absolutek:平台路径配置中心键（自定义上传对绝路径使用）
 * xt_path_urlk:平台路径配置中心键（自定义上传路径 自定义URL地址）
 * xt_path_relativek:平台路径配置中心键（自定义上传相对路径）
 * llowedFileExtensions:['jpg','gif','png']
 **/
var fileUploadResultArray = [];
function initGraphFile(graph){
    fileUploadResultArray.push('0');
    var allowedFileExtensions_ = ['xml'];
    var maxFileSize_ = 0;
    $('.graphXml').fileinput('clear');
    $("#graphXml").attr("class","file-loading")
    $("#graphXml").fileinput({
        showUpload:true, //是否显示上传按钮
        autoReplace : true,
        showCaption:true,
        showPreview:true,
        overwriteInitial:true,//覆盖已存在的文件
        uploadUrl:baseUrl+'import',
        enctype:'multipart/form-data',
        language:'zh',
        allowedFileExtensions:allowedFileExtensions_,//接收的文件后缀
        minFileCount:1,
        uploadAsync:true,/**默认异步上传**/
        showCaption:true,/**是否显示标题**/
        maxFileSize:maxFileSize_,/**单位为kb，如果为0表示不限制文件大小**/
        maxFileCount:1,/**表示允许同时上传的最大文件个数**/
        enctype:'multipart/form-data',
        validateInitialCount:true,
        browseClass : "btn btn-info m-btn m-btn--custom m-btn--icon", //按钮样式
        msgFilesTooMany:"选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        uploadExtraData:function (previewId, index) {
            var data = {
            };
            return data;
        }
    }).on('filebatchuploadsuccess', function(event, data, previewId, index) {
        for(var i = 0; i < fileUploadResultArray.length; i++){
            if(i == 0){
                var obj = data.response;
                loadXml(graph,obj.mxgraphxml);
                resetZxLine(graph);
                //关闭上传窗口
                $('#jehcImportModal').modal('hide');
                $('#graphXml').val('');
                $("#graphXml").fileinput('reset'); //重置上传控件（清空已文件）
                $('.graphXml').fileinput('destroy');
                $("#graphXml").removeAttr("class","file-loading")

                // if(obj.data.jsonID != 0){
                //     //关闭上传窗口
                //     $('#jehcImportModal').modal('hide');
                //     //并清空上传控件内容
                //     $('#graphXml').val('');
                //     $("#graphXml").fileinput('reset'); //重置上传控件（清空已文件）
                //     window.parent.toastrBoot(3,obj.data.msg);
                // }else{
                //     window.parent.toastrBoot(4,obj.data.msg);
                // }
                fileUploadResultArray.splice(0,fileUploadResultArray.length);
                i--;
                break;
            }
        }
    });
}

/**
 * 导入
 * @param graph
 * @param history
 */
function imp(graph,history){
    graph_refresh = graph;
    var jehcImportModalCount = 0 ;
    $('#jehcImportModal').modal({backdrop: 'static', keyboard: false});
    $('#jehcImportModalLabel').html("选择要导入的文件");
    $('#jehcImportModal').on("shown.bs.modal",function(){
        $("#jehcImportForm")[0].reset();
        if(++jehcImportModalCount == 1){
            initGraphFile(graph);
        }
    })
}

/**
 *
 * @param id
 */
function doImpl(id){
    msgTishCallFnBoot("确定导入该文件？",function(){

    })
}

/**
 *
 * @param graph
 */
function initData(graph){
    if(null != $("#graph_site_id").val() && '' != $("#graph_site_id").val()){
        ajaxBRequestCallFn(monitorModules+'/graphSite/get/'+$('#graph_site_id').val(),{},function(result){
            $("#graph_site_id").val(result.data.graph_site_id);
            $("#graph_site_name").val(result.data.graph_site_name);
            $("#gridBackGround").val(result.data.background);
            $("#gridColor").val(result.data.gridColor);
            $("#showGrid").val(result.data.showGrid);
            $("#gridSize").val(result.data.gridSize);
            //操作颜色
            setTimeout(function(){
                var background = result.data.background;
                if(null != background  && '' != background){
                    ThizViewPort.editorUi.setBackgroundColor(background);//设置背景样式方法一
                }
                var gridColor = result.data.gridColor;
                var gridSize =  result.data.gridSize;
                var showGrid = result.data.showGrid;
                if(null != showGrid && showGrid == 0){
                    if(null != gridColor && '' != gridColor){
                        ThizViewPort.editorUi.setGridColor(gridColor);//设置网格颜色
                        console.log("ThizViewPort.editorUi.editor.graph.view.gridColor ",ThizViewPort.editorUi.editor.graph.view.gridColor); //获取网格颜色
                    }
                    if(null != gridSize && '' != gridSize){
                        graph.gridSize = gridSize;// 更改布局网格大小
                    }
                }
                // ThizViewPort.editorUi.editor.graph.background = "#000"//设置背景样式方法二
                console.log("ThizViewPort.editorUi.editor.graph.background",ThizViewPort.editorUi.editor.graph.background);//获取背景颜色
            },0);

            loadXml(graph,result.data.graph_site_mxgraph);
        });
    }
}
$(document).ready(function(){
    var graph_site_id = GetQueryString("graph_site_id");
    $("#graph_site_id").val(graph_site_id);
});

/**
 * 设置背景图片
 * @param graph
 */
function setBackgroundImage(graph,imageSrc){
    // var img = new mxImage(imageSrc,1280 ,1024);  // w:1280   h:1024
    // graph.setBackgroundImage(img);
    // graph.view.validate();
    setTimeout(function(){
            // ThizViewPort.editorUi.setGridColor("#000");//设置网格颜色
            // console.log("ThizViewPort.editorUi.editor.graph.view.gridColor ",ThizViewPort.editorUi.editor.graph.view.gridColor); //获取网格颜色
            //
            // ThizViewPort.editorUi.setBackgroundColor("#000")
            // ThizViewPort.editorUi.editor.graph.background = "#000"//获取背景颜色
            // console.log("ThizViewPort.editorUi.editor.graph.background",ThizViewPort.editorUi.editor.graph.background);
        // ThizViewPort.editorUi.setBackgroundImage(imageSrc);
        // console.log("-----------",editorUi);

        //设置背景图片
        var img = new mxImage(imageSrc,1280 ,1024);  // w:1280   h:1024
        graph.setBackgroundImage(img);
        graph.view.validate();
    },0);
}

/**
 * 导出选中
 * @param graph
 */
function exportSelected(graph){
    var selected = graph.getSelectionCell();

    var xmlDoc = mxUtils.createXmlDocument();
    var root = xmlDoc.createElement('output');
    xmlDoc.appendChild(root);
    var xmlCanvas = new mxXmlCanvas2D(root);

    var scale=graph.getView().scale;
    var stackLayout = new mxStackLayout(graph, true);
    var border=stackLayout.border;
    var bounds = graph.getGraphBounds();

    //求选中图形的坐标，坐标原点在左上
    var cells = graph.model.cells;
    var x = selected.geometry.x;
    var y = selected.geometry.y;
    for(var i in cells){	 // cells 类数组对象 没有长度属性 和 数组的方法
        if (i > 1 && cells[i].parent.id == 1 && cells[i].edge != true) {
            if (cells[i].geometry.x < x  ) {
                x = cells[i].geometry.x;
            }
            if (cells[i].geometry.y < y ) {
                y = cells[i].geometry.y;
            }
        }
    }
    //整幅图与局部图的坐标差
    var dX = x - selected.geometry.x;
    var dY = y - selected.geometry.y;
    xmlCanvas.translate(
        Math.floor((border / scale - bounds.x + dX) / scale),
        Math.floor((border / scale - bounds.y + dY) / scale)
    );
    xmlCanvas.scale(1);
    var graphRoot = _.cloneDeep(graph.model.root); //lodash的方法
    //剔除没有选中的要素
    for (var i = 0;i<graphRoot.children[0].children.length;i++){
        var cell = graphRoot.children[0].children[i];
        if (cell != selected){
            graphRoot.children[0].children.splice(i,1);
        }
    }
    var imgExport = new mxImageExport();
    imgExport.drawState(graph.getView().getState(graphRoot), xmlCanvas);
    var w = selected.geometry.width;
    var h = selected.geometry.height;
    var xml = mxUtils.getXml(root);

    //提交至后台
}